import Cell from "./Cell.js"
import Snake from "./Snake.js"

class Model {
    constructor(xCount, yCount, width, height) {
        this.xCount = xCount
        this.yCount = yCount
        this.width = width
        this.height = height
        this.cellsize = width / xCount
        this.map = [] // 默认地图，没有障碍
        this.snake = new Snake(0, 0) // 默认位置为 (0, 0)
        // this.direction = 'left'
        this.food = null
        this.initFood()
        // this.status = true
        this.prompt_font_size = 100
        this.fontFamily = 'sans-serif'
    }

    /**
     * {
     *  x: []
     *  y: []
     * }
     * @param {*} obstacles 
     */
    initMap(obstacles = []) {
        for (let i = 0; i < this.yCount; i++) {
            if (obstacles[i] === undefined) {
                obstacles[i] = []
            }
            map[i] = []
            for (let j = 0; j < this.xCount; j++) {
                if (obstacles[i][j] !== undefined) {
                    map[i][j] = obstacles[i][j]
                    continue
                }
                map[i][j] = null
            }
        }

        initFood()
    }

    initFood() {
        const items = this.snake.toList()
        
        while (true) {
            let x = Math.floor(Math.random() * this.xCount);
            let y = Math.floor(Math.random() * this.yCount);
            const result = items.some(item => {
                return item.x === x && item.y === y
            })
            if (!result) {
                let r = Math.ceil(Math.random() * 255);
                let g = Math.ceil(Math.random() * 255);
                let b = Math.ceil(Math.random() * 255);
                this.food = new Cell(x, y, this.cellsize, `rgb(${ r }, ${ g }, ${ b })`)
                console.log(this.food);
                return this.food
                // break
            }
        }

        
    }

    /**
     * 
     * @param {*} snake 数组，包含有若干个节点，表示每个cell的坐标
     */
    createSnake(list) {
        // console.log('create snake');
        this.snake = new Snake(list[0].x, list[0].y, this.cellsize)
        for (let i = 1; i < list.length; i++) {
            this.snake.eat(new Cell(list[i].x, list[i].y, this.cellsize))
        }
        // console.log(this.snake);
        // console.log(this.snake.toList());

        if (this.head === this.foo) {
            this.direction = 'right'
        } else if (list.length == 2) {
            // 设置方向
        }
    }

    setMap(map) {
        this.map = map
    }
}

export default Model